import { defineStore } from 'pinia';
import bus from 'vue3-eventbus';

export const useWebSocketStore = defineStore('wos-webSocket', {
  actions: {
    // 主动关闭心跳包机制
    closeHeartbeat(): void {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = undefined;
      }
    },
    connect(url: string) {
      // console.log(url, this.ws);
      if (
        !this.ws ||
        this.ws.readyState === undefined ||
        this.ws.readyState === WebSocket.CLOSED
      ) {
        this.url = url;
        this.ws = new WebSocket(url);
        this.handleConnection();
      }

      bus.emit('ws-open', {
        readyState: this.ws.readyState,
        message: '连接成功',
      });
    },
    disconnect() {
      bus.emit('ws-disconnect', {
        readyState: WebSocket.CLOSED,
        message: '连接断开',
      });
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.close();
      }
      this.resetState();
    },
    send(data: string) {
      if (this.ws && this.ws.readyState === WebSocket.OPEN && data) {
        this.ws.send(data);
      }
    },
    handleConnection() {
      this.ws?.addEventListener('open', this.onOpen);
      this.ws?.addEventListener('message', this.onMessage);
      this.ws?.addEventListener('close', this.onClose);
      this.ws?.addEventListener('error', this.onError);
    },
    onClose(event: CloseEvent) {
      this.isConnected = false;
      if (!event.wasClean) {
        this.reconnect();
      }
      this.closeHeartbeat();
      bus.emit('ws-close', {
        readyState: WebSocket.CLOSED,
        message: '连接关闭',
      });
    },
    onError(_event: Event) {
      bus.emit('ws-error', {
        readyState: WebSocket.CLOSED,
        message: '连接错误',
      });
      this.closeHeartbeat();
    },
    onMessage(event: MessageEvent) {
      const data = event.data;
      let completeMessage = '';
      const messageRegex = /\[@\]([\s\S]*?)\[#\]/; // 使用正则表达式匹配完整的消息

      const match = (data as string).match(messageRegex);
      if (match) {
        completeMessage = match[1] as string; // 提取中间的内容
      } else {
        this.buffer += data; // 将接收到的数据存入缓冲区

        let index;
        index = this.buffer.indexOf('[#]');
        while (index !== -1) {
          const message = this.buffer.slice(0, Math.max(0, index + 3)); // 提取完整的消息
          this.buffer = this.buffer.slice(Math.max(0, index + 3)); // 从缓冲区中移除已处理的部分

          const startIndex = message.indexOf('[@]') + 3;
          completeMessage = message.slice(startIndex, index); // 提取中间的内容
          index = this.buffer.indexOf('[#]');
        }
      }
      completeMessage = completeMessage.replace(messageRegex, ''); // 移除已经匹配的消息部分
      bus.emit('ws-message', completeMessage);
      this.startHeartbeat();
    },
    onOpen(_event: Event) {
      bus.emit('ws-open', {
        readyState: WebSocket.OPEN,
        message: '连接成功',
      });
      this.isConnected = true;
      this.reconnectAttempts = 0; // 重置重连次数
      this.startHeartbeat();
    },
    reconnect() {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        bus.emit('ws-reconnect', {
          maxReconnectAttempts: false,
          message: `尝试重新连接 ${this.reconnectAttempts + 1}次`,
        });
        this.reconnectAttempts++;
        setTimeout(() => {
          this.connect(this.ws?.url as string); // 尝试重新连接
        }, 2000); // 每次重连等待2秒
      } else {
        this.closeHeartbeat();
        bus.emit('ws-reconnect', {
          maxReconnectAttempts: true,
          message: '已达到最大重新连接尝试次数，停止重新连接尝试。',
        });
      }
    },

    resetState() {
      this.isConnected = false;
      this.reconnectAttempts = 0;
      this.ws = null;
    },
    // >开始心跳检测 -> 定时发送心跳消息
    startHeartbeat(): void {
      if (!this.isConnected) return;
      if (this.heartbeatTimer) {
        this.closeHeartbeat();
      }
      this.heartbeatTimer = setInterval(() => {
        if (this.ws) {
          // this.ws.send(JSON.stringify({ data: {}, type: 'HeartBeat' }));
        } else {
          bus.emit('ws-error', {
            readyState: WebSocket.CLOSED,
            message: '连接已关闭',
          });
        }
      }, this.heartbeatInterval);
    },
  },
  persist: true,
  state: () => ({
    buffer: '',
    heartbeatInterval: 30_000, // 心跳包发送间隔，单位为毫秒
    heartbeatTimer: undefined as NodeJS.Timeout | undefined,
    isConnected: false,
    maxReconnectAttempts: 5, // 可以根据需求调整
    reconnectAttempts: 0,
    url: '',
    ws: null as null | WebSocket,
  }),
});
